package org.tom.basic.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.tom.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 工具类获取当前登录的用户信息
 */
public class LoginContextUtil {
    public static Logininfo getLoginContext(){
        //请求: RequestContextHolder是SpringMVC中的一个请求上下文工具，里面有ServletRequestAttributes
        //而：ServletRequestAttributes里面有请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        //拿到请求对象
        HttpServletRequest request = requestAttributes.getRequest();

        return getLoginContext(request);
    }

    public static Logininfo getLoginContext(HttpServletRequest request){
        // 获取请求头中携带的token
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)){
            // 获取spring容器
            WebApplicationContext requiredWebApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            // 通过容器获取bean,也就是spring中的对象
            RedisTemplate redisTemplate = (RedisTemplate) requiredWebApplicationContext.getBean("redisTemplate");
            // 去redis数据库中存的数据
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj!=null){
                return (Logininfo) obj;
            }
        }
        return null;
    }
}
